/*
 * UserProfileServlet.java
 * 作用：处理用户"用户中心"页面的请求，获取用户的详细信息和收货地址。
 */
package com.campustradingwall.controller.user;

import com.campustradingwall.dao.AddressDao;
import com.campustradingwall.dao.UserDao;
import com.campustradingwall.dao.RatingDao;
import com.campustradingwall.model.Address;
import com.campustradingwall.model.User;
import com.campustradingwall.model.Rating;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/user/profile")
public class UserProfileServlet extends HttpServlet {
    private UserDao userDao = new UserDao();
    private AddressDao addressDao = new AddressDao();
    private RatingDao ratingDao = new RatingDao();

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        
        if (user == null) {
            response.sendRedirect(request.getContextPath() + "/login.jsp");
            return;
        }

        // 刷新用户信息，以防过时
        user = userDao.getUserById(user.getId());
        session.setAttribute("user", user);

        List<Address> addresses = addressDao.getAddressesByUserId(user.getId());
        request.setAttribute("addresses", addresses);

        // 获取用户的评价信息
        List<Rating> receivedRatings = ratingDao.getRatingsByRatedUserId(user.getId());
        double averageRating = ratingDao.getAverageRatingForUser(user.getId());

        request.setAttribute("receivedRatings", receivedRatings);
        request.setAttribute("averageRating", averageRating);

        // 处理从其他页面（如购买页）传来的提示信息
        String message = (String) session.getAttribute("message");
        if (message != null) {
            request.setAttribute("message", message);
            session.removeAttribute("message"); // 显示后即移除
        }

        request.getRequestDispatcher("/user/profile.jsp").forward(request, response);
    }
} 